package com.huanletao.sync.synch01;

/**
 * 消费者
 */
public class Consumer {

    private CountNum countNum;


    public Consumer(CountNum countNum) {
        this.countNum = countNum;
    }

    public synchronized void Consume() {
        while (countNum.getCount() <= 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        try {
            Thread.sleep(500);
            countNum.setCount(countNum.getCount() - 1);
            System.out.println(Thread.currentThread().getName() + "消费-1,当前count：" + countNum.getCount());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //当前数量为0
        if (countNum.getCount()==0){
            notify();
        }

    }

    public synchronized void Produce() {
        while (countNum.getCount() >= 20) {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        if (countNum.getCount() >= 5){
            notify();
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        countNum.setCount(countNum.getCount() + 1);
        System.out.println(Thread.currentThread().getName() + "生产+1,当前count：" + countNum.getCount());
    }

}

